package cn.px.rest.controller.verify;

import com.google.code.kaptcha.Producer;
import cn.px.common.util.R;
import cn.px.common.validation.group.AddGroup;
import cn.px.common.validation.group.OtherGroup;
import cn.px.dao.dto.verify.VerifyCodeDTO;
import cn.px.service.verify.VerifyCodeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * 验证码接口
 *
 * @author
 */
@AllArgsConstructor
@Slf4j
@Controller
@RequestMapping("/verify")
public class VerifyCodeController {

    private final VerifyCodeService verifyCodeService;

    private final Producer producer;


    /**
     * 发送验证码
     *
     * @param verifyCodeDTO 短信DTO
     * @return R
     */
    @ResponseBody
    @PostMapping("/sms/code/send")
    public R save(@Validated({AddGroup.class}) @RequestBody VerifyCodeDTO verifyCodeDTO) {
        return new R<>(verifyCodeService.sendSmsCode(verifyCodeDTO));
    }

    /**
     * 校验图片验证码
     *
     * @param verifyCodeDTO 短信DTO
     * @return R
     */
    @ResponseBody
    @PostMapping("/captcha")
    public R valid(@Validated({OtherGroup.class}) @RequestBody VerifyCodeDTO verifyCodeDTO) {
        return new R<>(verifyCodeService.validCaptchaCode(verifyCodeDTO.getRandomStr(), verifyCodeDTO.getCaptchaCode(), true));
    }

    /**
     * 发送图片验证码
     *
     * @return R
     */
    @GetMapping("/captcha/{randomStr}")
    public void captcha(@PathVariable("randomStr") String randomStr, HttpServletResponse response) throws Exception {
        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        //保存验证码信息
        verifyCodeService.sendCaptchaCode(randomStr, text);

        // 转换流信息写出
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            ImageIO.write(image, "jpeg", os);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
}
